package com.yfjin.ffmpeg52

import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import kotlin.concurrent.thread


//音频都要解码重采样，因为要适配具体硬件
class MainActivityAudio : AppCompatActivity() {

    companion object {
        init {
            System.loadLibrary("audio-native-lib")
        }
    }

    external fun playAudio(url: String): Int

    private var audioTrack: AudioTrack? = null
    private var mButton:Button?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        mButton=findViewById(R.id.v_play)

        mButton?.setOnClickListener {
            playAudio()
        }
    }

    private fun playAudio() {
        val folderurl = File(Environment.getExternalStorageDirectory(), "input.mp4").getAbsolutePath();
        thread {
            playAudio(folderurl)
        }
    }

    //---------------------------------------------------------------

    fun createTrack(sampleRateInHz: Int, channel: Int) {

        var channelConfig: Int
        if (channel == 2) {
            channelConfig = AudioFormat.CHANNEL_OUT_STEREO
        } else {
            channelConfig = AudioFormat.CHANNEL_OUT_MONO
        }

        val bufferSize = AudioTrack.getMinBufferSize(
            sampleRateInHz,
            channelConfig,
            AudioFormat.ENCODING_PCM_16BIT
        )

        audioTrack = AudioTrack(
            AudioManager.STREAM_MUSIC,
            sampleRateInHz,
            channelConfig,
            AudioFormat.ENCODING_PCM_16BIT,
            bufferSize,
            AudioTrack.MODE_STREAM
        )
        audioTrack?.play()
    }


    fun playTrack(buffer:ByteArray,lenght:Int){
        if (audioTrack!=null&&audioTrack!!.playState==AudioTrack.PLAYSTATE_PLAYING){
            audioTrack!!.write(buffer,0,lenght)
        }
    }

}